<template>
  <div id="vipExchangePage">
    <h2 style="margin-bottom: 16px">会员码兑换</h2>

    <!-- 兑换码表单 -->
    <a-form name="formData" layout="vertical" :model="formData" @finish="handleSubmit">
      <a-form-item name="vipCode" label="兑换码">
        <a-input
          v-model:value="formData.vipCode"
          placeholder="请输入会员兑换码"
          allow-clear
          :maxlength="16"
        />
      </a-form-item>

      <a-form-item>
        <div class="action-buttons">
          <a-button type="primary" html-type="submit" style="width: 100%" :loading="loading">
            兑换
          </a-button>
          <a-button type="link" @click="showContactModal" class="contact-btn">
            <template #icon>
              <MessageOutlined />
            </template>
            联系作者
          </a-button>
        </div>
      </a-form-item>
    </a-form>

    <ContactAuth
      ref="contactAuthRef"
      qr-code-src="src/assets/wechat-qrcode.png"
      contact-text="微信号：zjb1370594838"
      title="联系技术支持"
      description="扫码添加微信以获取帮助"
    />
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { MessageOutlined } from '@ant-design/icons-vue'
import { exchangeVipUsingPost } from '@/api/userController.ts'
import { useRouter } from 'vue-router'
import ContactAuth from '@/components/ContactAuth.vue'

const formData = reactive<API.VipExchangeRequest>({
  vipCode: ''
})

const loading = ref(false)
const router = useRouter()

const contactAuthRef = ref<InstanceType<typeof ContactAuth>>()

const showContactModal = () => {
  contactAuthRef.value?.showModal()
}

const handleSubmit = async () => {
  if (!formData.vipCode.trim()) {
    message.error('请输入兑换码')
    return
  }

  loading.value = true
  try {
    const res = await exchangeVipUsingPost({
      vipCode: formData.vipCode
    })

    if (res.data.code === 0 && res.data.data) {
      message.success('兑换成功！')
      router.push({ path: '/' })
    } else {
      message.error('兑换失败：' + res.data.message)
    }
  } catch (error) {
    message.error('兑换失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
#vipExchangePage {
  max-width: 720px;
  margin: 0 auto;
  padding: 24px;
}

.action-buttons {
  position: relative;
  width: 100%;
}

.contact-btn {
  position: absolute;
  right: 0;
  bottom: -32px;
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.qr-code-image {
  width: 200px;
  height: 200px;
  margin: 16px 0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
